package com.controller;

import com.domain.User;
import com.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class UserComtroller {
    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/login")
    public String tologin(){
        return "login";
    }
    @PostMapping("/login")
    public String login(User user, HttpSession session,Model model) throws Exception {
        User u = userService.login(user);
        if (u != null){
            session.setAttribute("USER_SESSION",u);
            return "admin";
        }
        model.addAttribute("error","用户名或密码错误！");
        return "login";
    }
    @GetMapping("/update")
    public ModelAndView update(){
        return new ModelAndView("template/update");
    }
    @PostMapping("/update")
    public ModelAndView updatepwd(String oldpwd,String newpwd,HttpSession session){
        ModelAndView modelAndView = new ModelAndView("template/update");
        User user = (User) session.getAttribute("USER_SESSION");
        if (user.getPassword().equals(oldpwd)){
            User user2 = new User();
            user2.setId(user.getId());
            user2.setPassword(newpwd);
            userService.updatepwd(user2);
            session.setAttribute("USER_SESSION",userService.login(user2));
            modelAndView.addObject("msg","修改成功！");
            return modelAndView;
        }
        modelAndView.addObject("msg","修改失败，请重新尝试！");
        return modelAndView;
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }
}
